<template>
    <div class="container">
        <header>
            <h1>个人中心</h1>
            <el-button @click="openDialog" type="primary" style="margin-right: 60px">修改个人信息</el-button>
        </header>

        <!-- 搜索框 -->
        <el-input
            placeholder="根据Id、电影名、类型查询"
            v-model="inputVal"
            @keyup.enter.native="Search_table"
            clearable
        ></el-input>

        <!-- 电影列表 -->
        <el-table :data="paginatedData" style="width: 100%">
<!--            <el-table-column prop="id" label="ID" width="180">-->
<!--                <template slot-scope="scope">-->
<!--                    <div>{{ scope.row.movieId }}</div>-->
<!--                </template>-->
<!--            </el-table-column>-->
            <el-table-column type="expand" width=20>
                <template slot-scope="scope">
                    <div style="left: 50px"> <p>电影主演：</p>{{ scope.row.movieCast }}</div>
                    <div style="max-width: 95%;right: 30px"><p>电影详情：</p>{{ scope.row.movieReview }}</div>
                    <el-form label-position="left" inline class="demo-table-expand"></el-form>
                </template>
            </el-table-column>
            <el-table-column prop="poster" label="电影海报" width="100">
                <template slot-scope="scope">
<!--                    <div>{{ scope.row.movieId }}</div>-->
                    <img src="../../../../assets/images/noPoster.png" alt="" referrerpolicy="no-referrer" style="width: 100%;height: 100%" v-if="scope.row.moviePoster===''||scope.row.moviePoster.isEmpty">
                    <img :src=scope.row.moviePoster alt="" referrerpolicy="no-referrer" style="width: 100%;height: 100%" v-else>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="电影名" width="180">
                <template slot-scope="scope">
                    <div>{{ scope.row.movieName }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="电影类型">
                <template slot-scope="scope">
                    <div>{{ scope.row.movieType }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="content" label="电影导演">
                <template slot-scope="scope">
                    <div>{{ scope.row.movieDirector }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="content" label="国家">
                <template slot-scope="scope">
                    <div>{{ scope.row.movieNation }}</div>
                </template>
            </el-table-column>
            <el-table-column prop="content" label="语言">
                <template slot-scope="scope">
                    <div>{{ scope.row.movieLanguage }}</div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button type="text" @click="cancelFavourite(scope.row.movieId)">取消收藏</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            :key="paginationKey"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="filteredData.length"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
        ></el-pagination>

        <!-- 修改用户信息弹窗 -->
        <el-dialog
            title="编辑用户信息"
            :visible.sync="dialogVisible"
            @close="resetForm"
        >
            <el-form :label-width="formLabelWidth">
                <el-form-item label="用户ID">
                    <el-input v-model="userInfo.userChangeId" disabled></el-input>
                </el-form-item>

                <el-form-item label="用户名">
                    <el-input v-model="userInfo.userName" placeholder="请输入用户名"></el-input>
                </el-form-item>

                <el-form-item label="密码">
                    <el-input
                        v-model="userInfo.userPassword"
                        placeholder="请输入密码"
                        type="password"
                        @blur="validatePassword(userInfo.userPassword)"
                    ></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm">取消</el-button>
                <el-button type="primary" @click="saveUserInfo">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getFavouriteMovies, deleteFavouriteMovie } from '../../../../api/favouriteMovie'
import {mapGetters} from 'vuex'
import {editUser, updateUser} from '../../../../api/user'
import store from '../../../../store'

export default {
  data () {
    return {
      illegal: '`~!@#$%^&*()_+-=【】、{}|：“；‘《》？/。，<>?.,":;[]（）——·！……',
      i: 0,
      paginationKey: 0,
      inputVal: '', // 搜索框的值
      currentPage: 1, // 当前页
      pageSize: 5, // 每页显示的记录数
      movies: [], // 收藏的电影列
      dialogVisible: false, // 弹窗显示状态
      userInfo: {
        userChangeId: '',
        userName: '',
        userPassword: ''
      },
      formLabelWidth: '80px' // 表单标签宽度
    }
  },
  computed: {
    ...mapGetters({
      userId: 'user/getUserId',
      userName: 'user/getUserName'
    }),
    filteredData () {
      const query = this.inputVal.trim().toLowerCase()
      if (!Array.isArray(this.movies) || this.movies.length === 0) return []
      return this.movies.filter(item => {
        return (
          !query ||
                  (item.movieId && item.movieId.toString().includes(query)) ||
                  (item.movieName && item.movieName.toLowerCase().includes(query)) ||
                  (item.movieType && item.movieType.toLowerCase().includes(query))
        )
      })
    },
    paginatedData () {
      // 在搜索结果的基础上进行分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = this.currentPage * this.pageSize
      return this.filteredData.slice(start, end) // 使用 filteredData 作为分页基础
    }
  },
  watch: {
    inputVal (newVal) {
      this.currentPage = 1 // 每次搜索时，默认跳转到第一页
      this.paginationKey += 1 // 更新 key 以强制刷新分页组件
    }
  },
  methods: {
    isVisitor () {
      if (this.userName === '游客') {
        this.$message({
          message: '请登录',
          type: 'warning'
        })
        this.$router.push({path: '/login'})
      }
    },
    validatePassword (name, password) {
      if (!name) {
        this.$message.error('用户名不能为空，请输入用户名')
        return false
      }
      for (this.i = 0; this.i < this.illegal.length; this.i++) {
        if (name.indexOf(this.illegal.charAt(this.i)) !== -1) {
          this.$message.error('用户名存在非法字符，请重新输入')
          return false
        }
      }
      if (!password) {
        this.$message.error('密码不能为空，请输入密码')
        return false
      }
      if (password.length < 6) {
        this.$message.error('密码长度必须超过6个字符，请重新输入')
        return false
      }
      if (password.length > 18) {
        this.$message.error('密码长度不能超过18个字符，请重新输入')
        return false
      }
      for (this.i = 0; this.i < this.illegal.length; this.i++) {
        if (password.indexOf(this.illegal.charAt(this.i)) !== -1) {
          this.$message.error('密码存在非法字符，请重新输入')
          return false
        }
      }
      return true
    },
    async fetchMovies () {
      // 获取 userId
      const userId = this.userId

      if (!userId) {
        this.$message.error('用户未登录或用户ID无效')
        return
      }

      // 调用后端接口获取该用户的收藏电影
      try {
        const response = await getFavouriteMovies(userId)
        if (response.data && Array.isArray(response.data)) {
          this.movies = response.data // 设置电影数据
        } else {
          this.movies = [] // 如果没有数据，确保 movies 为一个空数组
        }
      } catch (error) {
        console.error('获取收藏电影失败:', error)
        this.movies = [] // 错误时清空电影列表
        this.$message.error('获取电影信息失败')
      }
    },

    cancelFavourite (movieId) {
      if (!movieId) {
        this.$message.error('无效的电影ID')
        return
      }
      // 使用计算属性获取的 this.userId
      deleteFavouriteMovie(this.userId, movieId)
        .then(() => {
          this.$message.success('取消收藏成功')
          this.fetchMovies() // 刷新收藏列表
        })
        .catch(error => {
          console.error('Failed to delete movie:', error)
        })
    },

    handlePageChange (page) {
      this.currentPage = page
    },

    openDialog () {
      // 打开弹窗时加载用户信息
      this.userInfo.userChangeId = this.userId || '' // 从 Vuex 中加载当前用户 ID
      // 模拟加载其他用户信息，可以通过接口获取
      this.userInfo.userName = localStorage.getItem('userName') || ''
      this.userInfo.userPassword = '' // 密码默认不显示，需重新输入
      this.dialogVisible = true
    },

    resetForm () {
      // 重置表单
      this.userInfo = {
        userChangeId: '',
        userName: '',
        userPassword: ''
      }
      this.dialogVisible = false
    },

    async saveUserInfo () {
      try {
        // 验证密码是否合法
        if (!this.validatePassword(this.userInfo.userName, this.userInfo.userPassword)) {
          return
        }

        // 调用 API 编辑用户信息
        const response = await editUser({
          userId: this.userInfo.userChangeId,
          userName: this.userInfo.userName,
          userPassword: this.userInfo.userPassword
        })

        if (response) {
          this.$message.success('用户信息已保存')
          store.dispatch('user/updateUserInfo', this.userInfo.userName)
          this.dialogVisible = false
        } else {
          this.$message.error('保存失败：用户名可能已存在')
        }
      } catch (error) {
        console.error('保存用户信息失败', error)
        this.$message.error('保存失败：服务器异常')
      }
    },
    async submitForm () {
      try {
        const response = await updateUser(this.userInfo)
        if (response.code === 200) {
          this.$message.success('用户信息更新成功')
          this.userInfo = response.data // 更新本地用户数据
        } else {
          this.$message.error(response.message || '更新失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
      }
    }
  },

  created () {
    this.isVisitor()
    this.fetchMovies() // 初始化时加载数据
  }
}
</script>

<style scoped>
@import "../../../../assets/styles/center.css";
</style>
